package test.se.fk.klistret.migrate.service;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLEncoder;

import javax.xml.bind.JAXBException;

import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.mock.MockDispatcherFactory;
import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse;
import org.jboss.resteasy.plugins.spring.SpringBeanProcessor;
import org.jboss.resteasy.plugins.spring.SpringResourceFactory;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.resteasy.util.HttpResponseCodes;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.GenericXmlApplicationContext;

import com.klistret.cmdb.utility.resteasy.AccessControlInterceptor;
import com.klistret.cmdb.utility.resteasy.ApplicationExceptionMapper;
import com.klistret.cmdb.utility.resteasy.InfrastructureExceptionMapper;
import com.klistret.cmdb.utility.resteasy.IntegerMessageBodyWriter;

public class ModuleService {

	/**
	 * Mock dispatcher
	 */
	private static Dispatcher dispatcher;

	/**
	 * Spring application context
	 */
	private static GenericXmlApplicationContext ctx;

	@BeforeClass
	public static void runBeforeClass() throws Exception {
		// Embedded server
		dispatcher = MockDispatcherFactory.createDispatcher();

		// Load up the processor and build a spring factory
		SpringBeanProcessor processor = new SpringBeanProcessor(dispatcher,
				null, null);

		ctx = new GenericXmlApplicationContext();
		ctx.getEnvironment().setActiveProfiles("development");
		ctx.load("classpath:Spring.cfg.xml");
		ctx.refresh();
		ctx.addBeanFactoryPostProcessor(processor);

		// Add service to the dispatcher
		SpringResourceFactory moduleService = new SpringResourceFactory(
				"moduleService", ctx,
				se.fk.klistret.migrate.service.ModuleService.class);
		dispatcher.getRegistry().addResourceFactory(moduleService);

		// Necessary providers
		ResteasyProviderFactory providerFactory = dispatcher
				.getProviderFactory();
		providerFactory.registerProvider(ApplicationExceptionMapper.class);
		providerFactory.registerProvider(InfrastructureExceptionMapper.class);
		providerFactory.registerProvider(AccessControlInterceptor.class);
		providerFactory.registerProvider(IntegerMessageBodyWriter.class);
	}

	@Test
	public void module() throws JAXBException, URISyntaxException,
			UnsupportedEncodingException {
		MockHttpRequest request = MockHttpRequest
				.get("/resteasy/migrate/module?directory="
						+ URLEncoder.encode("C:\\temp\\module", "UTF-8")
						+ "&fileName="
						+ URLEncoder.encode("module.del", "UTF-8"));

		MockHttpResponse response = new MockHttpResponse();
		dispatcher.invoke(request, response);

		Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT,
				response.getStatus());
	}
}
